package typejump.gui;

import javax.swing.*;

import typejump.Messenger;
import typejump.Settings;
import typejump.TypeJump;
import typejump.engine.GameEngine;
import typejump.engine.OnGoingThing;
import typejump.objects.GameObject;
import typejump.objects.Llamow;
import typejump.objects.Player;
import typejump.objects.Surface;
import typejump.objects.SwagDropItem;

import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
import java.util.LinkedList;

public class EditorPanel extends JPanel {

	private JTextField filterField;
	private JPanel libraryPanel;
	private ObjectPanel editingPanel;
	private LinkedList<GameObject> objectLibrary = new LinkedList<GameObject>();
	private Hashtable<Class<GameObject>, PropertyMediator> mediators;
	
	public EditorPanel() {
		
		mediators = new Hashtable<Class<GameObject>, PropertyMediator>();

		filterField = new JTextField(10);
		libraryPanel = new JPanel();
		libraryPanel.setLayout(new BoxLayout(libraryPanel, BoxLayout.Y_AXIS));
		editingPanel = new ObjectPanel();

		setLayout(new BorderLayout());
		
		Box topPanel = Box.createVerticalBox();
		//topPanel.add(filterField);
		topPanel.add(editingPanel);

		add(topPanel, BorderLayout.NORTH);
		add(new JScrollPane(libraryPanel), BorderLayout.CENTER);

		objectLibrary.add(SwagDropItem.createObject(""));
		objectLibrary.add(Player.createObject(Settings.getDouble("player.width") + " " + Settings.getDouble("player.height")));
		objectLibrary.add(Surface.createObject("brick"));
		objectLibrary.add(Surface.createObject("brick2"));
		objectLibrary.add(Llamow.createObject(""));

		updateObjectLibrary();
	}
	
	public void editObject(GameObject object) {
		if (mediators.containsKey(object.getClass())) {
			PropertyMediator med = mediators.get(object.getClass());
			editingPanel.setMediator(med);
		}
	}

	private boolean passesFilter(GameObject o) {
		return true;
	}

	private void updateObjectLibrary() {
		libraryPanel.removeAll();
		for (GameObject o : objectLibrary) {
			if (!passesFilter(o))
				continue;
			JButton button = new JButton(new ImageIcon(o.generateThumbnail(40,
					40)));
			button.addActionListener(new AdderListener(o));
			libraryPanel.add(button);
		}
		libraryPanel.invalidate();
		try {
			invalidate();
			validate();
			doLayout();
		} catch (Exception e) {

		}
	}
	
	class AdderListener implements ActionListener {
		private GameObject o;
		public AdderListener(GameObject o) {
			this.o = o;
		}
		public void actionPerformed(ActionEvent e) {
			final GameObject obj = o.clone();
			if (obj != null) {
				obj.centerX(TypeJump.getInst().getMouseX());
				obj.centerY(TypeJump.getInst().getMouseY());
				
				if (obj instanceof Player)
					GameEngine.setFocusOnPlayer(false);
				GameEngine.addObject(obj);
				
				GameEngine.pass("DevGrab", obj);
			}
		}
	}
}
